//
// Created by xiaofoo.
//

#include "TclInterpController.h"

TclInterpController *TclInterpController::_pinstance{nullptr};
// std::mutex TclInterpController::_mutex;
pthread_once_t TclInterpController::_ponce = PTHREAD_ONCE_INIT;

TclInterpController::TclInterpController(Tcl_Interp *interp) {
  _interp = interp;
}

TclInterpController::~TclInterpController() {}

void TclInterpController::init() {
  Tcl_Interp *interp = Tcl_CreateInterp();
  _pinstance = new TclInterpController(interp);
}

TclInterpController *TclInterpController::getInstance() {
  //  std::lock_guard<std::mutex> lock(_mutex);
  //  if (_pinstance == nullptr) {
  //    Tcl_Interp *interp = Tcl_CreateInterp();
  //    _pinstance = new TclInterpController(interp);
  //  }
  pthread_once(&_ponce, &TclInterpController::init);
  return _pinstance;
}

void TclInterpController::shutdown() {
  if (_pinstance != nullptr) {
    Tcl_DeleteInterp(_pinstance->_interp);
    Tcl_Finalize();
    _pinstance->_interp = nullptr;
    _pinstance = nullptr;
  }
}

void TclInterpController::executeCommand(const std::string &command) {
  if (Tcl_Eval(_pinstance->_interp, command.c_str()) != TCL_OK) {
    std::string error_msg = Tcl_GetStringResult(_pinstance->_interp);
    error_msg = "ERROR: " + error_msg;
    std::cerr << error_msg << std::endl;
  }
}

Tcl_Interp *TclInterpController::interp() const { return _interp; }
